﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace XMM.Controls.Library
{
    /// <summary>
    /// Interaktionslogik für AudioInfo.xaml
    /// </summary>
    public partial class Holster_AudioInfo : UserControl
    {
        public Objects.AudioInfo CurrentAudioInfo { get; set; }

        public string SelectedFilePath { get; set; }

        StackPanel spnTracks = new StackPanel();
        BitmapImage bmpTracks;

        StackPanel spnChannels = new StackPanel();
        BitmapImage bmpChannels;

        StackPanel spnLanguages = new StackPanel();

        ProcessingSplash dlgSplashScreen = new ProcessingSplash();

        public Holster_AudioInfo()
        {
            InitializeComponent();

            CurrentAudioInfo = new Objects.AudioInfo();
            spnTracks.Orientation = Orientation.Horizontal;
            spnTracks.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            spnChannels.Orientation = Orientation.Horizontal;
            spnChannels.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            spnLanguages.Orientation = Orientation.Vertical;
            spnLanguages.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            spnLanguages.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

            bmpTracks = new BitmapImage(new Uri(@"../../images/bin/tracks.png", UriKind.Relative));
            bmpChannels = new BitmapImage(new Uri(@"../../images/bin/channels_64.png", UriKind.Relative));
        }

        public void AnalyseAudio()
        {
            if (this.IsEnabled == true)
            {
                if (System.IO.File.Exists(SelectedFilePath))
                {
                    Thread thAnalysis = new Thread(new ThreadStart(doAnalysis));
                    thAnalysis.Start();

                    dlgSplashScreen = new ProcessingSplash();
                    if ((bool)dlgSplashScreen.ShowDialog())
                    {
                        dlgSplashScreen.Close();
                    }
                }
                else
                {
                    MessageBox.Show("Die Datei \"" + SelectedFilePath + "\" wurde nicht gefunden!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void doAnalysis()
        {
            Objects.AudioInfo oAudioInfo = new Objects.AudioInfo();
            try
            {
                // Create MediaInfoLib-Reference for the selected video-file.
                MediaInfoLib.MediaInfo oMediaInfo = new MediaInfoLib.MediaInfo();
                oMediaInfo.Open(SelectedFilePath);

                // Get Info for all audio-tracks.
                int iCurrentAudioTrack = 0;

                while (true)
                {
                    try
                    {
                        // Get Audio-Codec.
                        string sCodec = oMediaInfo.Get(MediaInfoLib.StreamKind.Audio, iCurrentAudioTrack, "Codec");
                        if (sCodec == String.Empty)
                            break;
                        else
                        {
                            oAudioInfo.AudioCodecs.Add(sCodec);
                        }

                        // Get Language from Track-Name.
                        string sLanguage = oMediaInfo.Get(MediaInfoLib.StreamKind.Audio, iCurrentAudioTrack, "Language");
                        string sNormalizeLanguage = Functions.LanguageTools.getNormalizedLanguage(sLanguage);
                        oAudioInfo.Languages.Add(sNormalizeLanguage);

                        // Get Best Audio-Channel-Track.
                        string sChannels = oMediaInfo.Get(MediaInfoLib.StreamKind.Audio, iCurrentAudioTrack, "Channels");
                        double dChannels = double.Parse(sChannels);
                        if (dChannels > oAudioInfo.Channels)
                            oAudioInfo.Channels = dChannels;
                    }
                    catch (Exception ex)
                    {
                        break;
                    }

                    ++iCurrentAudioTrack;
                }
                
               
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler beim Analysieren der Datei \"" + SelectedFilePath + "\": " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            this.Dispatcher.Invoke(new killSplashCallback(killSplash));
            this.Dispatcher.Invoke(new setAudioInfoCallback(setAudioInfo), new object[] { oAudioInfo });
            this.Dispatcher.Invoke(new loadInfoCallback(loadInfo));
        }

        private void setAudioInfo(Objects.AudioInfo oInfo)
        {
            CurrentAudioInfo = oInfo;
        }

        private delegate void setAudioInfoCallback(Objects.AudioInfo oInfo);

        private void killSplash()
        {
            if (dlgSplashScreen != null)
            {
                try
                {
                    dlgSplashScreen.Close();
                }
                catch (Exception ex)
                {
                }
            }
        }

        private delegate void killSplashCallback();

        public void loadInfo()
        {
            wrpAudioInfo.Children.Clear();

            if (CurrentAudioInfo != null)
            {
                // Setup Tracks
                spnTracks.Children.Clear();
                Image imgTracks = new Image();
                imgTracks.Width = 22;
                imgTracks.Height = 22;
                imgTracks.Source = bmpTracks;
                spnTracks.Children.Add(imgTracks);
                Label lblTracks = new Label();
                lblTracks.Content = CurrentAudioInfo.Tracks.ToString();
                spnTracks.Children.Add(lblTracks);

                // Setup Audio-Channels (Best Option)
                spnChannels.Children.Clear();
                Image imgChannels = new Image();
                imgChannels.Width = 22;
                imgChannels.Height = 22;
                imgChannels.Source = bmpChannels;
                spnChannels.Children.Add(imgChannels);
                Label lblChannels = new Label();
                lblChannels.Content = CurrentAudioInfo.Channels.ToString();
                spnChannels.Children.Add(lblChannels);

                // Setup Audio-Languages (Set Audio-Channels as Tooltip)
                spnLanguages.Children.Clear();
                Label lblHeadline = new Label();
                lblHeadline.Content = "Sprachen";
                lblHeadline.FontSize = 9;
                lblHeadline.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                lblHeadline.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                spnLanguages.Children.Add(lblHeadline);
                if (CurrentAudioInfo.Languages.Count > 0)
                {
                    foreach (string sLanguage in CurrentAudioInfo.Languages)
                    {
                        Image imgLanguage = new Image();
                        imgLanguage.Width = 20;
                        imgLanguage.Height = 20;
                        imgLanguage.Source = new BitmapImage(new Uri(@"../../images/lang/" + Functions.LanguageTools.getNormalizedLanguage(sLanguage) + ".png", UriKind.Relative));
                        imgLanguage.ToolTip = sLanguage;
                        spnLanguages.Children.Add(imgLanguage);
                    }
                }
                else
                {
                    Label lblNoLanguage = new Label();
                    lblNoLanguage.Content = "Keine Info";
                    lblNoLanguage.FontSize = 9;
                    lblNoLanguage.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    lblNoLanguage.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                    spnLanguages.Children.Add(lblNoLanguage);
                }

                // Add to wrpAudioInfo
                wrpAudioInfo.Children.Add(spnTracks);
                wrpAudioInfo.Children.Add(spnChannels);
                wrpAudioInfo.Children.Add(spnLanguages);

                // Setup Codec-Icons
                if (CurrentAudioInfo.IsDolbySurround)
                {
                    Image imgDolbySurround = new Image();
                    imgDolbySurround.Width = 24;
                    imgDolbySurround.Height = 24;
                    imgDolbySurround.Source = new BitmapImage(new Uri(@"../../images/bin/dolby.png", UriKind.Relative));
                    int iAudioChannel = CurrentAudioInfo.AudioCodecs.IndexOf("AC3");
                    imgDolbySurround.ToolTip = "Kanal " + iAudioChannel.ToString() + " (" + CurrentAudioInfo.Languages[iAudioChannel] + ")";
                    wrpAudioInfo.Children.Add(imgDolbySurround);
                }

                if (CurrentAudioInfo.IsDolbyDigital)
                {
                    Image imgDolbyDigital = new Image();
                    imgDolbyDigital.Width = 24;
                    imgDolbyDigital.Height = 24;
                    imgDolbyDigital.Source = new BitmapImage(new Uri(@"../../images/bin/dd.png", UriKind.Relative));
                    int iAudioChannel = CurrentAudioInfo.AudioCodecs.IndexOf("DD");
                    imgDolbyDigital.ToolTip = "Kanal " + iAudioChannel.ToString() + " (" + CurrentAudioInfo.Languages[iAudioChannel] + ")";
                    wrpAudioInfo.Children.Add(imgDolbyDigital);
                }

                if (CurrentAudioInfo.IsDTS)
                {
                    Image imgDTS = new Image();
                    imgDTS.Width = 24;
                    imgDTS.Height = 24;
                    imgDTS.Source = new BitmapImage(new Uri(@"../../images/dts.png", UriKind.Relative));
                    int iAudioChannel = CurrentAudioInfo.AudioCodecs.IndexOf("DTS");
                    imgDTS.ToolTip = "Kanal " + iAudioChannel.ToString() + " (" + CurrentAudioInfo.Languages[iAudioChannel] + ")";
                    wrpAudioInfo.Children.Add(imgDTS);
                }
            }
        }

        public delegate void loadInfoCallback();

        private void btnRefreshAudioInfo_Click(object sender, RoutedEventArgs e)
        {
            AnalyseAudio();
        }
    }
}
